//
//  LGButton.swift
//  Play
//
//  Created by lingo on 2017/8/4.
//  Copyright © 2017年 letus. All rights reserved.
//  一行代码调整button中 图片和文字的位置

import Foundation
import UIKit
//记img的位置
enum LGButtonLayoutStyle {
    case LGButtonLayoutStyleTop// image在上，label在下
    case LGButtonLayoutStyleLeft// image在左，label在右
    case LGButtonLayoutStyleBottom // image在下，label在上
    case LGButtonLayoutStyleRight // image在右，label在左
  }

extension UIButton {
    
    func layoutButtonWithEdgeInsetsStyle(layoutStyle style:LGButtonLayoutStyle,imgTitleSpace space:CGFloat) -> Void{
        let imageWidth : CGFloat = (self.imageView?.frame.size.width)!
        let imageHeight : CGFloat = (self.imageView?.frame.size.height)!
        var labelWidth : CGFloat?
        var labelHeight : CGFloat?
    
        var imageEdgeInsets : UIEdgeInsets?
        var labelEdgeInsets : UIEdgeInsets?
//高于8.0
        if #available(iOS 8.0, *) {
            labelWidth = self.titleLabel?.intrinsicContentSize.width
            labelHeight = self.titleLabel?.intrinsicContentSize.height
        }else{
            labelWidth = self.titleLabel?.frame.size.width;
            labelHeight = self.titleLabel?.frame.size.height;
        }
        switch style {
            case .LGButtonLayoutStyleTop:
                imageEdgeInsets = UIEdgeInsets.init(top: -labelHeight!-space/2.0, left: 0, bottom: 0, right: -labelWidth!)
                labelEdgeInsets = UIEdgeInsets.init(top: 0, left: -imageWidth, bottom: -imageHeight-space/2.0, right: 0)
            break
            case .LGButtonLayoutStyleLeft:
                imageEdgeInsets = UIEdgeInsets.init(top: 0, left: -space/2.0, bottom: 0, right: space/2.0)
                labelEdgeInsets = UIEdgeInsets.init(top: 0, left: space/2.0, bottom: 0, right: -space/2.0)
            break
            case .LGButtonLayoutStyleBottom:
                imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 0, bottom: -labelHeight!-space/2.0, right:-labelWidth!)
                labelEdgeInsets = UIEdgeInsets.init(top: -imageHeight-space/2.0, left: -imageWidth, bottom: 0, right: 0)
            break
            case .LGButtonLayoutStyleRight:
                imageEdgeInsets = UIEdgeInsets.init(top: 0, left: labelWidth!+space/2.0, bottom: 0, right:-labelWidth!-space/2.0)
                labelEdgeInsets = UIEdgeInsets.init(top: 0, left: -imageWidth-space/2.0, bottom: 0, right: imageWidth+space/2.0)
            break
        }
        self.titleEdgeInsets = labelEdgeInsets!;
        self.imageEdgeInsets = imageEdgeInsets!;
    }
}
